import os
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from utils.logger import get_logger
from api.routers import reports, people, frameworks, projects, health
from utils.config import settings

# 获取日志记录器
logger = get_logger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时的初始化
    try:
        logger.info("🚀 牛马工时日志汇报系统 API 启动中...")
        logger.info(f"📖 API 文档地址: http://localhost:{settings.API_PORT}/docs")
        logger.info(f"🔍 RedDoc 文档地址: http://localhost:{settings.API_PORT}/redoc")
        logger.info(f"🔧 API 前缀: {settings.API_PREFIX}")
        logger.info(f"🔧 环境模式: {settings.APP_ENV}")
        logger.info(f"🤖 AI 服务状态: {'启用' if settings.ai_enabled else '禁用'}")
        
        if settings.ai_enabled:
            logger.info(f"🧠 AI 模型: {settings.DEEPSEEK_MODEL}")
            logger.info(f"🔗 AI 服务地址: {settings.DEEPSEEK_BASE_URL}")
        
        # 测试数据库连接
        from database import get_db_client
        db_client = get_db_client()
        if db_client.test_connection():
            logger.info("✅ 数据库连接测试成功")
        else:
            logger.warning("⚠️ 数据库连接测试失败")
            
        logger.info("✅ API 服务启动完成")
        
    except Exception as e:
        logger.error(f"❌ API 启动过程中发生错误: {e}")
        raise
    
    yield
    
    # 关闭时的清理
    try:
        logger.info("🔥 牛马工时日志汇报系统 API 正在关闭...")
        logger.info("🧹 清理资源中...")
        # 这里可以添加其他清理逻辑，比如关闭数据库连接池等
        logger.info("✅ 资源清理完成")
        logger.info("👋 牛马工时日志汇报系统 API 已安全退出")
    except Exception as e:
        logger.error(f"❌ 资源清理过程中发生错误: {e}")


# 创建 FastAPI 应用
app = FastAPI(
    title=settings.API_TITLE,
    description=settings.API_DESCRIPTION,
    version=settings.API_VERSION,
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan
)

# CORS 中间件配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境中应该限制特定域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(health.router, prefix=settings.API_PREFIX, tags=["Health"])
app.include_router(reports.router, prefix=settings.API_PREFIX, tags=["Reports"])
app.include_router(people.router, prefix=settings.API_PREFIX, tags=["People"])
app.include_router(frameworks.router, prefix=settings.API_PREFIX, tags=["Frameworks"])
app.include_router(projects.router, prefix=settings.API_PREFIX, tags=["Projects"])

if __name__ == "__main__":
    import uvicorn
    import signal
    import sys
    
    def signal_handler(signum, frame):
        """信号处理器 - 优雅退出"""
        logger.info("🛑 收到退出信号，正在优雅关闭服务...")
        sys.exit(0)
    
    # 注册信号处理器
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    try:
        logger.info(f"🌐 启动服务器: {settings.API_HOST}:{settings.API_PORT}")
        logger.info(f"🔧 调试模式: {settings.DEBUG}")
        logger.info(f"🔧 环境模式: {settings.APP_ENV}")
        logger.info(f"📊 数据库地址: {settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_NAME}")
        logger.info("📝 按 Ctrl+C 优雅退出")
        
        uvicorn.run(
            "api.main:app",
            host=settings.API_HOST,
            port=settings.API_PORT,
            reload=settings.DEBUG,
            access_log=True,
            log_config=None  # 使用我们自定义的日志配置
        )
        
    except KeyboardInterrupt:
        logger.info("🛑 接收到键盘中断信号 (Ctrl+C)")
        logger.info("👋 牛马工时日志汇报系统 API 已优雅退出")
        sys.exit(0)
        
    except Exception as e:
        logger.error(f"❌ 服务启动失败: {e}")
        sys.exit(1)
        
    finally:
        logger.info("🔄 清理资源完成") 